<template>
    <el-dialog :model-value="CombinationWordDialog" :show-close="false" modal-class="customize-dialog"
        :append-to-body="true" :close-on-click-modal="false" align-center width="1000px">
        <template #header="{ titleId, titleClass }">
            <div class="flex justify-between items-center dialog-header">
                <div class="flex items-center">
                    <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
                </div>
                <div class="flex items-center">
                    <svg-icon size="16px" icon-class="close-line" @click="closeDialog"></svg-icon>
                </div>
            </div>
        </template>
        <div>
            <Tabs v-model="state.activeIndex" @update:model-value="handleTabClick" active-color="#ffffff">
                <template v-for="(item, index) in combinations" :key="index">
                    <TabItem :icon="item.icon" :label="item.label" path="" :quantity="item.Value" :index="index">
                        <div class="mt-10px combination-checkbox h-400px">
                            <el-scrollbar :always="true">
                                <div class="custom-checkbox-group flex-wrap">
                                    <el-checkbox-group v-model="selectedKeywords"
                                        class="flex !flex-row flex-wrap w-full">
                                        <div class="flex items-center w-33.33%" v-for="word in item.list"
                                            :key="word.label">
                                            <el-checkbox :value="word.label" :label="word.label"></el-checkbox>
                                        </div>
                                    </el-checkbox-group>
                                </div>
                            </el-scrollbar>
                        </div>
                    </TabItem>
                </template>
            </Tabs>
        </div>
        <div class="flex justify-between mt-16px mb-6px">
            <div class="flex items-center">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange">全选</el-checkbox>
                    <div class="ml-16px">已选中 <b class="text-color-blue">{{ selectedKeywords.length }}</b> 条数据</div>
            </div>
            <div>
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="closeDialog">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import Tabs from '@/components/Tab/First.vue'
import TabItem from '@/components/Tab/Item.vue'

const props = defineProps<{
    CombinationWordDialog: boolean,
    combinations: any[],
    title: string,
    id: number,
    checkAll: boolean,
    checkCombinationOptions: any[]
}>()

const emit = defineEmits(['closeDialog', 'confirm','checked'])

const state = reactive({
    activeIndex: 0,
    combinationOptions: []
})

// 保存每个选项卡的选中关键词
const tabSelectedKeywords = ref<Record<number, string[]>>({});
const selectedKeywords = ref<string[]>([]);
const checkAll = ref(false);
const isIndeterminate = ref(false);

function closeDialog() {
    emit('closeDialog')
}

function handleTabClick(val: any) {
    const { index } = val

    // 保存当前选项卡的选中状态
    tabSelectedKeywords.value[state.activeIndex] = [...selectedKeywords.value];

    // 切换到新的选项卡
    state.activeIndex = index;

    // 恢复新选项卡的选中状态，如果没有记录则初始化为空数组
    selectedKeywords.value = tabSelectedKeywords.value[index] || [];

    // 更新全选状态
    updateCheckAllState();
}

// 全选/全不选处理函数
function handleCheckAllChange(val: string | number | boolean) {
    const currentList = props.combinations[state.activeIndex]?.list || [];
    if (val) {
        // 全选
        selectedKeywords.value = currentList.map((item: any) => item.label);
    } else {
        // 全不选
        selectedKeywords.value = [];
    }
    isIndeterminate.value = false;

    // 保存当前选项卡的选中状态
    tabSelectedKeywords.value[state.activeIndex] = [...selectedKeywords.value];
}

// 更新全选状态
function updateCheckAllState() {
    const currentList = props.combinations[state.activeIndex]?.list || [];
    const checkedCount = selectedKeywords.value.length;
    const totalCount = currentList.length;

    checkAll.value = checkedCount === totalCount && totalCount > 0;
    isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount;
}

function handleCancel(){
    //取消prop.checkCombinationOptions里的选中
    const selects = selectedKeywords.value
    
    // 修复：使用过滤方法而不是在遍历时删除元素
    // 原来的代码在遍历数组时修改数组会导致索引错乱，部分元素无法被正确删除
    for (let i = props.checkCombinationOptions.length - 1; i >= 0; i--) {
        if (selects.includes(props.checkCombinationOptions[i])) {
            props.checkCombinationOptions.splice(i, 1)
        }
    }

    //取消选中
    selectedKeywords.value = []
    //取消prop.checkCombinationOptions里的选中
    closeDialog()
}

watch(() => selectedKeywords.value, (newVal) => {
    // 修复访问combinations数组中当前活动tab的list
    const activeCombination = props.combinations[state.activeIndex];
    if (activeCombination && activeCombination.list) {
        activeCombination.list.forEach((item: any) => {
            // 检查当前项的label是否在selectedKeywords.value中
            if (newVal.includes(item.label)) {
                // 如果找到匹配项，将value设为1
                item.value = 1;
            } else {
                // 如果未找到匹配项，将value设为0
                item.value = 0;
            }
        });
    }
    // 更新全选状态
    updateCheckAllState();

    // 保存当前选项卡的选中状态
    tabSelectedKeywords.value[state.activeIndex] = [...newVal];

    emit('checked', newVal)
})

watch(() => props.CombinationWordDialog, () => { 
    props.combinations.forEach((combination, index) => {
        combination.list.forEach((item: any) => {
            if (props.checkCombinationOptions.includes(item.label)) {
                selectedKeywords.value.push(item.label);
            }
        });
    });
    
    
}, { immediate: true })
</script>

<style lang="scss" scoped>

</style>